
from wepapi.models import user, Department
from wepapi.utils.Pagination import Pagination
from django.shortcuts import render, HttpResponse, redirect
from django.urls import reverse
from django import forms

from wepapi.utils.bootstrap import BootStrapModelForm
from wepapi.utils.form import UserFrom

def user_list(request):
    """用户列表"""
    userList = user.objects.all()
    page_object = Pagination(request, userList)

    context = {
        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 生成页码
    }
    return render(request, 'user_list.html', context)
    # for item in userList:
    #     item.depart_id #获取数据库中存储的那个字段
    #     xx=Department.objects.filter(id=item.id).first()
    #     print(xx)
    #     item.depart  #根据id自动去关联的表中获取哪一行数据depart对象


"""添加用户"""


def user_add(request):
    # 原始方式
    # ufrom = UserFrom()
    if request.method == "GET":
        context = {
            'gender_choices': user.GENDER_CHOICES,
            'department_list': Department.objects.all(),
            # 'ufrom': ufrom
        }

        return render(request, "user_add.html", context)
        pass
    # 获取用户post提交过来的数据（roleName输入为空）
    name = request.POST.get("name")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("account")
    create_time = request.POST.get("create_time")
    gender = request.POST.get("gender")
    depart = request.POST.get("rolename")

    # 保存到数据库
    user.objects.create(name=name, pwd=pwd, age=age, account=account, create_time=create_time, gender=gender,
                        depart_id=depart)
    return redirect(reverse("user_list"))


###### ModelForm  示例    ######################################################################
# widget = {
#     'name': forms.TextInput(attrs={
#         'class': 'form-control',
#         'placeholder': '请输入姓名',
#         'style': 'margin-left: 25px;'
#     }),


class UserFrom(BootStrapModelForm):
    # name = forms.CharField(min_length=2, label="姓名")

    class Meta:
        model = user
        fields = ["name", "pwd", "age", "account", "create_time", "gender", "depart"]

    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     for name, field in self.fields.items():
    #         field.widget.attrs = {
    #             'class': 'form-control',
    #             'placeholder': '请输入' + field.label,
    #         }
    #         # if name == 'name':
    #         #     field.widget.attrs['placeholder'] = '请输入姓名'
    #         # elif name == 'pwd':
    #         #     field.widget.attrs['placeholder'] = '请输入密码'
    #         # elif name == 'age':
    #         #     field.widget.attrs['placeholder'] = '请输入年龄'
    #         # elif name == 'account':
    #         #     field.widget.attrs['placeholder'] = '请输入余额'
    #         # elif name == 'create_time':
    #         #     field.widget.attrs['placeholder'] = '请输入入职时间'
    #         # elif name == 'gender':
    #         #     field.widget.attrs['placeholder'] = '请选择性别'
    #         # elif name == '"depart"':
    #         #     field.widget.attrs['placeholder'] = '请选择部门'
    #         #
    #         # else:
    #         #     break





def user_model_form_add(request):
    """添加用户 (ModelFrom 版本)"""
    if request.method == "GET":
        uform = UserFrom()
        return render(request, 'user_model_form_add.html', {"uform": uform})

    # 用户Post提交数据 ,数据的检验.
    uform = UserFrom(data=request.POST)
    if uform.is_valid():
        print(uform.cleaned_data)
        # 如果数据合法,保存到数据库
        # user.objects.create(name=request.POST.get("name"), age=request.POST.get("age"), account=request.POST.get("account"),)
        uform.save()
        return redirect(reverse("user_list"))
    # 检验失败（在页面上显示错误信息）
    return render(request, 'user_model_form_add.html', {"uform": uform})





def user_del(request, id):
    """删除用户"""
    user.objects.filter(id=id).delete()
    return redirect(reverse("user_list"))



def user_edit(request, id):

    """编辑用户"""
    user_object = user.objects.filter(id=id).first()

    if request.method == "GET":
        ufrom = UserFrom(instance=user_object)
        return render(request, "user_edit.html", {"ufrom": ufrom})
    # 根据ID找到数据库中的数据并进行更新
    # request.POST.get("rolename") 获取用户提交的标题

    ufrom = UserFrom(data=request.POST, instance=user_object)
    if ufrom.is_valid():
        ufrom.save()
        return redirect(reverse("user_list"))

    return render(request, 'user_edit.html', {"ufrom": ufrom})